package com.packge;

import com.agent.T_04_DelegateAgent;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public final class AgentPackager {

    /** 1. 把 agentClass 和 adviceClass 打成临时 jar，返回磁盘路径 */
    public static Path buildTempAgentJar(byte[] agentClass,
                                         byte[] adviceClass,
                                         String agentClassName) throws IOException {
        // 放在 IDEA 系统缓存目录，重启 IDE 会自动清掉
        Path tmpDir = Paths.get("D:\\dev\\JavaProjects\\agent\\target");
        Files.createDirectories(tmpDir);
        Path jar = tmpDir.resolve("agent-1.0-SNAPSHOT.jar");

        Manifest mf = new Manifest();
        mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        mf.getMainAttributes().put(new Attributes.Name("Premain-Class"), agentClassName);
        mf.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
        mf.getMainAttributes().put(new Attributes.Name("Can-Retransform-Classes"), "true");

        try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(jar), mf)) {
            writeEntry(jos, agentClassName, agentClass);
            writeEntry(jos, agentClassName.replace("Agent", "Advice"), adviceClass);
        }
        return jar;
    }

    private static void writeEntry(JarOutputStream jos, String className, byte[] bytes) throws IOException {
        String entry = className.replace('.', '/') + ".class";
        jos.putNextEntry(new JarEntry(entry));
        jos.write(bytes);
        jos.closeEntry();
    }


}